const https = require('https')
// const http = require('http')

module.exports = async (ctx) => {
  // let url = 'http://route.showapi.com/341-2'
  // let url = "route.showapi.com/341-3?maxResult=20&page=3&showapi_appid=77211&showapi_sign=c9eb0bdd51264a77b6638f8cb15769cf"
  let url = "route.showapi.com"
  // let path = '/341-2'
  // let url = 'https://api.douban.com/v2/book/'+'1220561'
  const bookinfo = await getJoke(url)
  console.log('bookinfo', bookinfo);
  
  ctx.state.data = {
    'msg': bookinfo
  }
}

function getJoke(url) {
  return new Promise((reslove, reject) => {
    let data = {
    "showapi_appid": 77211,
    "showapi_sign": "c9eb0bdd51264a77b6638f8cb15769cf",
    "page":"1",
    "maxResult":"20"
    }
    let post_data = JSON.stringify(data);
      let options = {
        hostname: url,
        // port: 80,
        path: '/341-1?maxResult=20&page=3&showapi_appid=77211&showapi_sign=c9eb0bdd51264a77b6638f8cb15769cf',
        method: "POST",
        headers:{ 
          'Content-Type':'application/json',
        }
      }
    let req = https.request(options, res => {
      console.log('222222222');
      res.setEncoding('utf-8');
      let urlData = ''
      res.on('data', data=>{
        // urlData += data
        urlData = data
      })
      res.on('end', data => {
        // const bookinfo = JSON.parse(urlData)
        const bookinfo = urlData
        if(bookinfo.title){
          reslove(bookinfo)
        }
        reject(bookinfo)
      })
    })
    req.on('error', (e) => {
      console.log(`problem with request: ${e.message}`);
    });
    
    // write data to request body
    // req.write(post_data);
    req.end();
  })
}